package org.fig.ioc.overview.container;

import org.fig.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @Description: 不在Application的环境下也可以读取Bean信息
 * @Author: Flynn Vanderboom
 * @Data: 2021/6/11 0:21
 */

public class AnnotationApplicationContextAsIoCContainerDemo {
    public static void main(String[] args) {
        //创建BeanFactory容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        //将当前类  AnnotationApplicationContextAsIoCContainerDemo 作为配置类 (Configuration Class)
        context.register(AnnotationApplicationContextAsIoCContainerDemo.class);

        //启动应用上下文
        context.refresh();

        lookupByCollectionType(context);

        //关闭上下文
        context.close();
    }
    @Bean
    public User user(){
        User user = new User();
        user.setId(3);
        user.setName("小天");
        return user;
    }


    private static void lookupByCollectionType(BeanFactory beanFactory){
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找到所有的User的集合对象:"+users);
        }
    }
}
